<?php
    session_start();
    define("MINUTE", 60);
    define("HOUR", 3600); // 60 * 60 
    define("DAY", 86400); //  60 * 60 * 24 
    define("WEEK", 604800); // 60 * 60 * 24 * 7
    define("MONTH", 2592000); // 60 * 60 * 24 * 30
    define("YEAR", 31536000); // 60 * 60 * 24 * 365
    /**
     *Config class
     *handling get tweets,get blog posts
     *writing user details to DB etc..
     *@author Miqdad Ali K
     */
    class Config{
        public $my_twitter_name;
        public $my_last_tweet;
        public $my_last_tweet_time;
        public $tweet_page;
        public $my_last_blog_post_title;
        public $my_last_blog_post_desc;
        public $my_last_blog_post_url;
        public $my_last_blog_post_time;
        private $tweet_count;
        
        private $my_blog_rss_link;
        private $my_email;
        
        private $db_conn;
        private $quotes;
        private $dresses;
        
        /**
         *function __construct
         *constructor function
         *@param
         *@access
         *@return
         */
        function __construct(){
            $this->my_twitter_name = "miqdadali";
            $this->my_blog_rss_link = "http://ubersmith.blogspot.in/feeds/posts/default";
            $this->my_email = "miqdad@quintetsolutions.com";
            $this->tweet_count = 10;
            $this->dresses = array("white","black","wood");
            
            $this->createQuotes();
        }
        
        /**
         *function createQuotes
         *function to create quotes array
         *@param null
         *@access private
         *@return null
         */
        function createQuotes(){
            $this->quotes = array(
                "Leonardo da Vinci" => "Simplicity is the ultimate sophistication.",
                "Frank Lloyd Wright" => "Simplicity and repose are the qualities that measure the true value of any work of art.",
                "Charles Dudley Warner" => "Simplicity is making the journey of this life with just baggage enough.",
                "Plato" => "Beauty of style and harmony and grace and good rhythm depend on simplicity.",
                "Albert Einstein" => "Everything should be made as simple as possible, but not simpler.",
                "Henry Wadsworth" => "In character, in manner, in style, in all things, the supreme excellence is simplicity.",
                "Eleanor Roosevelt" => "A little simplification would be the first step toward rational living, I think.",
                "Richard Bach" => "The simplest things are often the truest.",
                "Henry Louis Mencken" => "For every problem there is a solution which is simple, clean and wrong.",
                "William Shakespeare" => "Simply the thing that I am shall make me live.",
                "Isaac Newton" => "Nature is pleased with simplicity.",
                "Eugene Delacroix" => "A taste for simplicity cannot last for long.",
                "David Hockney" => "Anything simple always interests me.",
                "Mahatma Gandhi" => "Let us learn to live simply, so that others may simply live",
                "Thomas Matthiessen" => "Life is beautiful in its simplicity.",
                "Charles Wagner" => "Simplicity is a state of mind.",
                "Bruce Lee" => "Simplicity is the key to brilliance.",
                "Philip James Bailey" => "Simplicity is natures first step, and the last of art.",
                "Jacob Lawrence" => "When the subject is strong, simplicity is the only way to treat it.",
            );
        }
        
        /**
         *function getRandomQuote
         *function to get random quote
         *@param
         *@access public
         *@return array
         */
        function getRandomQuote(){
            if(isset($_SESSION['quote_author'])){
                if($_SESSION['quote_time'] == date("Ymd")){
                    $author = $_SESSION['quote_author'];
                    $return = array();
                    $return['author'] = $author;
                    if(isset($this->quotes[$author])){
                        $return['quote'] = $this->quotes[$author];
                        return $return;
                    }
                }
            }
            $author = array_rand($this->quotes);
            $return = array();
            $return['author'] = $author;
            $return['quote'] = $this->quotes[$author];
            $_SESSION['quote_author'] = $author;
            $_SESSION['quote_time'] = date("Ymd");
            return $return;
        }
        
        /**
         *function connectDB
         *function for connection to DB
         *@param
         *@access private
         *@return
         */
        function connectDB(){
            /*if($this->db_conn = mysql_connect("sql102.byetcluster.com","b2_10388606","justHost")){
                mysql_select_db("b2_10388606_miqdadalik_com");
            }*/
            if($this->db_conn = mysql_connect("localhost","419609","nameserverfail")){
                mysql_select_db("419609");
            }
        }
        
        /**
         *function saveUserDetails
         *function to write user IP,user agent,refer etc.. to DB
         *@param
         *@access
         *@return
         */
        function saveUserDetails(){
            $this->connectDB();
            $user_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
            $user_agent = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
            $user_host = mysql_real_escape_string($_SERVER['REMOTE_HOST']);
            $user_refer = mysql_real_escape_string($_SERVER['HTTP_REFERER']);
            $date = date("Y-m-d H:i:s");
            $query = "
                INSERT INTO
                    tarcking(
                        user_ip,user_agent,user_host,user_referer,visited_date
                    )
                VALUES(
                    '$user_ip','$user_agent','$user_host','$user_refer','$date'
                )
            ";
            mysql_query($query,$this->db_conn);
        }
        
        /**
         *function getMyLastTweet
         *function to get last tweet using twitter API
         *@param
         *@access
         *@return
         */
        function getMyLastTweet(){
            $this->my_last_tweet ="";
            $this->my_last_tweet_time = "";
            $username = $this->my_twitter_name;
            $format = "json";
            $url = "http://api.twitter.com/1/statuses/user_timeline/$username.$format?count=1&page=".$this->tweet_page;
            if($data = file_get_contents($url,true)){
                $tweet=json_decode($data);
                $text = $tweet[0]->text;
                if($tweet_text = preg_replace("/http:\/\/([^\/]+)[^\s]*/", "<a href='$0' target='_blank'>$0$1</a>", $text)){
                    
                }
                if($tweet_text = preg_replace("/https:\/\/([^\/]+)[^\s]*/", "<a href='$0' target='_blank'>$0$1</a>", $tweet_text)){
                    
                }
                $this->my_last_tweet = $tweet_text;
                //$this->timeSince($tweet[0]->created_at)
                $this->my_last_tweet_time = date("jS F",strtotime($tweet[0]->created_at));     
            }
            else{
                $this->my_last_tweet = "Oops! can't read tweets";
            }
            
        }
        
        /**
         *function getMyTweets
         *function to get tweets using twitter API
         *@param
         *@access
         *@return array
         */
        function getMyTweets(){
            $username = $this->my_twitter_name;
            $format = "json";
            $url = "http://api.twitter.com/1/statuses/user_timeline/$username.$format?count=10";
            $return = array();
            $index = 0;
            if($data = file_get_contents($url,true)){
                $tweets = json_decode($data);
                foreach($tweets as $tweet){
                    $text = $tweet->text;
                    if($tweet_text = preg_replace("/http:\/\/([^\/]+)[^\s]*/", "<a href='$0' target='_blank'>$0$1</a>", $text)){
                    
                    }
                    if($tweet_text = preg_replace("/https:\/\/([^\/]+)[^\s]*/", "<a href='$0' target='_blank'>$0$1</a>", $tweet_text)){
                        
                    }
                    $return[$index]['text'] = $tweet_text;
                    $return[$index]['time'] = date("jS F",strtotime($tweet->created_at));
                    $index++;
                }
            }
            return $return;
        }
        
        /**
         *function changeDress
         *function to change theme
         *@param
         *@access
         */
        function changeDress(){
            $new_dress = "white";
            if(isset($_SESSION['dress'])){
                $new_dress = ( $_SESSION['dress'] == "white" ) ? "black" : ( ( $_SESSION['dress'] == "black" ) ? "wood" : (( $_SESSION['dress'] == "wood" ) ? "armored" : "white"));
            }
            $_SESSION['dress'] = $new_dress;
            
        }
        
        /**
         *function getMyLastBlogPost
         *function to get last post
         *@param
         *@access
         *@return
         */
        function getMyLastBlogPost(){
            $this->my_last_blog_post_title = "";
            $this->my_last_blog_post_desc = "";
            $this->my_last_blog_post_time = "";
            if($rss = simplexml_load_file($this->my_blog_rss_link)){
                if($rss){
                    $last_entry = $rss[0]->entry[0];
                    $this->my_last_blog_post_title = $last_entry->title;
                    $this->my_last_blog_post_desc =   trim(substr($last_entry->content,0,119),"  ");
                    $this->my_last_blog_post_url = $last_entry->link[4]['href'];
                    $this->my_last_blog_post_time = $this->timeSince($last_entry->published); 
                }
            }
            else{
                $this->my_last_blog_post_desc = "Oops! can't read blog post";
            }
        }
        
        /**
         *function sendMail
         *to send contact me request
         *@param $user_email,$user_name,$user_msg
         *@access
         *@return boolean
         */
        function sendMail($user_email,$user_name,$user_msg){
            $headers = 'From: Contact Me<contact_me@miqdadalik.com>' . "\r\n" .
            'Reply-To: '.$user_email . "\r\n" .
            'Content-Type: text/html; charset=UTF-8' . "\r\n" .
            'MIME-Version: 1.0' . "\r\n" .
            'Content-Transfer-Encoding: base64' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
            
            $mail = "From : $user_name <$user_email>";
            $mail .= "<br /><b>Message<b><br />";
            $mail .= $user_msg;
            
            if(mail($this->my_email,"New message from miqdadalik.com",$mail,$headers)){
                return true;
            }
            return false;
        }
        
        /**
         *function timeSince
         *to desplay time since format
         *@param $date
         *@access
         *@return time since format
         */
        function timeSince($date) {
            $since = abs(strtotime('now') - strtotime($date));
         
            if($since > YEAR) {
                $year = floor($since / YEAR);
                return "more than $year year(s) ago";
            }    
         
            if ($since > MONTH) {
                $month = floor($since / MONTH);
                return "about $month month(s) ago";
            } 
         
            if ($since > WEEK) {
                $week = floor($since / WEEK);
                $day = floor(($since - ($week * WEEK)) / DAY);
                return "about $week week(s), and $day day(s) ago";
            }
         
            if ($since > DAY) {        
                $day = floor($since / DAY);
                $hour = floor(($since - ($day * DAY)) / HOUR);
                return "about $day day(s), $hour hour(s) ago";
            }
         
            if ($since > HOUR) {        
                $hour = floor($since / HOUR);
                $minute = floor(($since - ($hour * HOUR)) / MINUTE);
                return "about $hour hour(s), $minute minute(s) ago";
            }
         
            if ($since > MINUTE) {        
                $minute = floor($since / MINUTE);
                return "$minute minute(s) ago";
            }
         
            return "under 1 minute ago";	
         
        }
        
        
    }
    
    if(isset($_GET['option']) and $_GET['option'] == "send_contact"){
        $name = ( isset($_GET['user_name']) and $_GET['user_name'] != "" ) ? $_GET['user_name'] : null;
        $email = ( isset($_GET['user_email']) and $_GET['user_email'] != "" ) ? $_GET['user_email'] : null;
        $message = ( isset($_GET['user_msg']) and $_GET['user_msg'] != "" ) ? $_GET['user_msg'] : null;
        $config = new Config();
        $return = array();
        $text = "Oops! something went wrong :(";
        $error = true;
        //if($name != null and $email != null and $message != null){
        if($config->sendMail($email,$name,$message)){
            $text = "Mail has been sent. Thank you for your time :)";
            $error = false;
        }
        //}
        $return['text'] = $text;
        $return['error'] = $error;
        echo json_encode($return);
        exit;
    }
    if(isset($_GET['option']) and $_GET['option'] == "save_user"){
        $config = new Config();
        $query = $config->saveUserDetails();
        $temp = array();
        echo json_encode($temp);
        exit;
    }
    if(isset($_GET['option']) and $_GET['option'] == "get_tweet"){
        $config = new Config();
        $return = array();
        $return['tweets'] = $config->getMyTweets();
        echo json_encode($return);
        exit;
    }
    if(isset($_GET['option']) and $_GET['option'] == "quotes"){
        $config = new Config();
        $return = array();
        $return = $config->getRandomQuote();
        echo json_encode($return);
        exit;
    }
    if(isset($_GET['option']) and $_GET['option'] == "change_dress"){
        $config = new Config();
        $config->changeDress();
        $temp = array();
        echo json_encode($temp);
        exit;
    }
    $config = new Config();
    $config->getMyLastBlogPost();
    $return['blog']['title'] = $config->my_last_blog_post_title;
    $return['blog']['desc'] = strip_tags($config->my_last_blog_post_desc);
    $return['blog']['time'] = $config->my_last_blog_post_time;
    $return['blog']['link'] = $config->my_last_blog_post_url;
    
    echo json_encode($return);
    
?>